<?php
/**
 * Created by.
 * User: littleU-569598569
 * Date: 2021/2/1 0001
 * Time: 20:26
 */

namespace app\api\service;
use app\api\model\AdminMenu as AdminMenuModel;


class AdminMenu
{
    public function setMenu($data)
    {
        $id = $data['id'];
        if($id == '')
        {
            return $this->addMenu($data);
        }
        else
        {
            return $this->updateMenu($data, $id);
        }
    }

    private function addMenu($data)
    {
        try
        {
            $obj = new AdminMenuModel($data);
            $obj->allowField(true)->save();
        }
        catch(\Exception $ex)
        {
            return json([
                'code' => config('code.error'),
                'msg'  => $ex->getMessage()
            ]);
        }
        return json([
            'code' => config('code.success'),
            'msg'  => '新增成功'
        ]);
    }

    private function updateMenu($data, $id)
    {
        try
        {
            $obj = new AdminMenuModel();
            $obj->allowField(true)->save($data, ['id'=>$id]);
        }
        catch(\Exception $ex)
        {
            return json([
                'code' => config('code.error'),
                'msg'  => $ex->getMessage()
            ]);
        }
        return json([
            'code' => config('code.success'),
            'msg'  => '修改成功'
        ]);
    }

    public function getMenuList()
    {
        $menus = (new AdminMenuModel())->with('pMenu')->where('status',config('code.normal'))->select();
        $menuList = $this->getTreeList($menus);
        return json([
            'code' => config('code.success'),
            'msg'  => '请求成功',
            'data' => $menuList
        ]);
    }

    private function getTreeList($menus, $pid=0, $level=0)
    {
        $tree = [];
        $prefix = '|';
        $prefix2 = '······';
        foreach($menus as $menu)
        {
            if ($menu['pid'] == $pid)
            {
                $menu['level'] = $level;
                if ($level > 0)
                {
                    $menu['title_prefix'] = $prefix . str_repeat($prefix2, $menu['level']) . $menu['title'];
                }
                else
                {
                    $menu['title_prefix'] = str_repeat($prefix2, $menu['level']) . $menu['title'];
                }
                $tree[] = $menu;
                $tree = array_merge($tree, $this->getTreeList($menus, $menu['id'], $level + 1));
            }
        }
        return $tree;
    }
}